import * as Types from './mutations-types'

const mutations = {
  // state是自动放入的，默认就是指的当前的state
  // [Types.INCREMENT]意思是取出Types里的INCREMENT值
  [Types.INCREMENT] (state, b) {
    // 传过来的参数不是数值型则返回
    let book = {
      bookCover: b.bookCover,
      bookName: b.bookName,
      bookInfo: b.bookInfo,
      bookPrice: b.bookPrice,
      bookId: b.bookId,
      count: 1
    }
    let collectBook = state.collect.find(item => {
      if (item.bookId === book.bookId) {
        return true
      }
      return false
    })
    //  如果没找到则是undefined
    if (!collectBook) {
      state.collect.push(book)
    } else {
      state.collect = state.collect.map(item => {
        //  找到id相同的那一本书,给数量加一
        if (item.bookId === book.bookId) {
          item.count++
          console.log(item.count)
          return item
        }
        // 其他书正常返回即可
        return item
      })
    }
  },
  [Types.DECREMENT] (state, book) {
    let collectBook = state.collect.find(item => item.bookId === book.bookId)
    if (!collectBook) {
      return
    }
    if (collectBook.count === 1) {
      state.collect = state.collect.filter(function (item) {
        return item.bookId !== book.bookId
      })
    } else {
      state.collect = state.collect.map(item => {
        //  找到id相同的那一本书,给数量加一
        if (item.bookId === book.bookId) {
          item.count--
          return item
        }
        // 其他书正常返回即可
        return item
      })
    }
  }
}

export default mutations
